package com.test.example.exception;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.xingluo.pay.exception.PayException;
import com.xingluo.system.satoken.AuthUtils;
import com.xingluo.tools.exception.CaptchaException;
import com.xingluo.tools.exception.ServiceException;
import com.xingluo.tools.exception.ToolsException;
import com.xingluo.tools.result.CodeMsg;
import com.xingluo.tools.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 
 * @author qiuyongjuan
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public Result handlerNotLoginException(NotLoginException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        // 不同异常返回不同状态码
        int code = 401;
        String message = "";
        if (e.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供令牌";
        } else if (e.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "未提供有效的令牌";
        } else if (e.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            code = 402;
            message = "登录信息已过期，请重新登录";
        } else if (e.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "您的账户已在另一台设备上登录，如非本人操作，请立即修改密码";
        } else if (e.getType().equals(NotLoginException.KICK_OUT)) {
            message = "已被系统强制下线";
        } else if (e.getType().equals(NotLoginException.TOKEN_FREEZE)) {
            // 设置了active-timeout，active-timeout时间内未操作，Token被冻结，需重新登陆
            message = "登录信息已过期，请重新登录";
        } else if (e.getType().equals(NotLoginException.NO_PREFIX)) {
            message = "未按照指定前缀提交 token";
        } else {
            message = "当前会话未登录";
        }
        // 退出清理redis中的登录缓存信息
        AuthUtils.logout();
        log.error("请求地址'{}',执行未登录失败'{}'", requestURI, e.getMessage());
        return Result.error(code, message);
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public Result handleAccessDeniedException(NotPermissionException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return Result.error(403, "没有权限，请联系管理员授权");
    }

    /**
     * 验证码校验异常
     */
    @ExceptionHandler(CaptchaException.class)
    public Result handleCaptchaException(CaptchaException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',验证码校验失败：'{}'", requestURI, e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 验证码校验异常
     */
    @ExceptionHandler(ToolsException.class)
    public Result handleToolsException(ToolsException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',工具操作失败：'{}'", requestURI, e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',业务异常：'{}'", requestURI, e.getMessage());
        return Result.error(e.getCode(), e.getMessage()) ;
    }

    /**
     * 支付异常
     */
    @ExceptionHandler(PayException.class)
    public Result handlePayException(PayException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',支付操作失败：'{}':'{}'", requestURI, e.getErrorCode(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                      HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return Result.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e, HttpServletRequest request)
    {
        log.error("请求地址'{}',传参校验异常：'{}'", request.getRequestURI(), e.getMessage());
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Result.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.error(message);
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return Result.error("服务器处理失败，请稍后再试");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return Result.error("服务器处理失败，请稍后再试");
    }

}
